package stack;

import java.util.Stack;

/**
 * 42. 接雨水
 */
public class P42 {
    public int trap(int[] height) {

        int totalWater = 0;
        Stack<Integer> stack = new Stack<>();
        Integer max = new Integer(height[0]);
        stack.push(max);

        // 左到右
        for (int i = 1; i < height.length; i++) {
            if (height[i] >= max) {
                while (stack.peek() != max) {
                    totalWater += max - stack.pop();
                }
                stack.pop();
                max = new Integer(height[i]);
                stack.push(max);
            } else {
                stack.push(height[i]);
            }
        }
        // 右到左
        int[] nums = new int[stack.size()];
        int idx=0;
        for (; !stack.isEmpty(); ) {
            nums[idx++] = stack.pop();
        }
        max = new Integer(nums[0]);
        stack.push(max);
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] >= max) {
                while (stack.peek() != max) {
                    totalWater += max - stack.pop();
                }
                stack.pop();
                max = new Integer(nums[i]);
                stack.push(max);
            } else {
                stack.push(nums[i]);
            }
        }
        return totalWater;
    }

    public static void main(String[] args) {
        int[] height = new int[]{2,0,2};
        int trap = new P42().trap(height);
        System.out.println(trap);
    }
}
